package com.coderising.kailuncen;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class Configuration {

	Map<String, ActionConfig> actionConfigMap = new HashMap<>();

	public Configuration() {
	}

	public Configuration(String name) {
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(name);

		SAXBuilder builder = new SAXBuilder();

		try {
			Document jdomDoc = builder.build(inputStream);
			Element rootElement = jdomDoc.getRootElement();
			for (Element child : rootElement.getChildren()) {
				String actionName = child.getAttributeValue("name");
				String className = child.getAttributeValue("class");
				ActionConfig actionConfig = new ActionConfig(actionName, className);
				for (Element sub : child.getChildren("result")) {
					String viewResult = sub.getAttributeValue("name");
					String viewPath = sub.getText().trim();
					actionConfig.addViewResult(viewResult, viewPath);
				}
				actionConfigMap.put(actionName, actionConfig);
			}
		} catch (JDOMException e) {
			throw new ConfigurationException(e);
		} catch (IOException e) {
			throw new ConfigurationException(e);
		}
	}

	public String getClassName(String name) {
		if (actionConfigMap.get(name) != null) {
			return actionConfigMap.get(name).getClassName();
		} else {
			return null;
		}

	}

	public String getViewResult(String actionName, String result) {
		if (actionConfigMap.get(actionName) != null) {
			return actionConfigMap.get(actionName).getViewResult().get(result);
		} else {
			return null;
		}
	}

	private class ActionConfig {
		private String name;
		private String className;
		private Map<String, String> viewResult = new HashMap<>();

		public ActionConfig(String name, String className) {
			this.name = name;
			this.className = className;
		}

		public ActionConfig() {
		}

		public void addViewResult(String result, String viewPath) {
			viewResult.put(result, viewPath);
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getClassName() {
			return className;
		}

		public void setClassName(String className) {
			this.className = className;
		}

		public Map<String, String> getViewResult() {
			return viewResult;
		}

		public void setViewResult(Map<String, String> viewResult) {
			this.viewResult = viewResult;
		}
	}
}
